package com.soil.code.generation.domain.code.service;

import com.soil.code.generation.domain.code.constant.CodeTemplateEnum;
import com.soil.code.generation.domain.code.entity.PersistentObject;
import com.soil.code.generation.domain.code.util.CodeGenerationUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import static freemarker.template.Configuration.VERSION_2_3_31;

/**
 * @author zeno
 */
@Service
public class CodeGenerationService{

  private static final String CODE_FILE_SUFFIX = ".java";

  private static final Configuration TEMPLATE_CFG;

  static {
    TEMPLATE_CFG = new Configuration(VERSION_2_3_31);

    try{
      TEMPLATE_CFG.setDirectoryForTemplateLoading(new File("F:\\workspce\\programming\\personal\\soil-web\\code-generation"
                                                  + "-service\\src\\main\\resources\\code-templates\\persistencetier"));
    } catch(IOException e){
      throw new RuntimeException(e);
    }
    TEMPLATE_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
    TEMPLATE_CFG.setDefaultEncoding("UTF-8");
    TEMPLATE_CFG.setLogTemplateExceptions(true);
    TEMPLATE_CFG.setWrapUncheckedExceptions(true);
  }

  public CodeGenerationService(){
  }

  public void generatePersistentCode( String outputDir, PersistentObject po ) throws IOException,
                                                                                     TemplateException{

    Template poTemplate = TEMPLATE_CFG.getTemplate(CodeTemplateEnum.PO.fileName());

    File codeFile = CodeGenerationUtils.createCodeFile(outputDir, po.getPkg(), po.getClassName());

    FileWriter codeFileWriter = new FileWriter(codeFile);
    poTemplate.process(po,codeFileWriter);

  }
}
